package factorytest.iflytek.com.einkiflytekfactorytest.factorytestui;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import factorytest.iflytek.com.einkiflytekfactorytest.FTFloatWindowService;
import factorytest.iflytek.com.einkiflytekfactorytest.R;
import factorytest.iflytek.com.einkiflytekfactorytest.device.DeviceAttr;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.DebugLog;



public class FactorySecondActivity extends FactoryBaseActivity {

    private boolean mViewItemsCreated = false;


    private static final float DEF_ITEM_VIEW_SIZE = 80.0f;

    private float itemViewSize = DEF_ITEM_VIEW_SIZE;

    private RelativeLayout parentContainer;
    Rect rectTemp = new Rect();

    private TextView txtInfo;

    private boolean isETP = false;

    private ServiceConnection serviceConnection = new MyServiceConnection();
    private FTFloatWindowService mBindService;

    private class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {

            FTFloatWindowService.MyBinder mBinder = (FTFloatWindowService.MyBinder) binder;
            mBindService = mBinder.getService();

            if (mBindService != null) {
                mBindService.setFloatLayoutVisibility(View.INVISIBLE);
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBindService = null;
        }

    }


    @Override
    int getLayoutId() {
        return R.layout.activity_factory_second;
    }

    @Override
    void onInitView(@Nullable Bundle savedInstanceState) {

        Intent intent = new Intent(this, FTFloatWindowService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);


        txtInfo = (TextView) findViewById(R.id.txtInfo);

        parentContainer = (RelativeLayout) findViewById(R.id.touch_draw_root_layout);

        final float size = getResources().getDimension(R.dimen.touch_draw_item_view_size);
        if (size > 0) {
            itemViewSize = size;
            DebugLog.e("touch draw item size = " + size);
        }

    }

    @Override
    void onHandleMessage(Handler handler, Message msg) {

    }

    @Override
    protected void onResume() {
        super.onResume();

        showInfo();

        if (mBindService != null) {
            mBindService.setFloatLayoutVisibility(View.INVISIBLE);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mBindService != null) {
            mBindService.setFloatLayoutVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unbindService(serviceConnection);
    }

    private void showInfo() {
        String useTool = getString(R.string.tp_test_use_finger);
        if (isETP) {
            useTool = getString(R.string.tp_test_use_electric_pen);
        }
        String info = getString(R.string.tp_test_info, useTool);
        txtInfo.setText(info);
        Toast.makeText(getContext(), useTool, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            createAllViewItems();
        }
    }

    private void createAllViewItems(){

        if( mViewItemsCreated )
            return ;
        mViewItemsCreated = true;
        CreateViewItems(mContext, parentContainer);
    }


    private void CreateViewItems(Context context, RelativeLayout parent) {

        parent.removeAllViews();

        int w = parent.getWidth();
        int h = parent.getHeight();

        if (w == 0 || h == 0) {
            DisplayMetrics dm = new DisplayMetrics();
            Display display = getWindowManager().getDefaultDisplay();

            display.getMetrics(dm);
            w = dm.widthPixels;
            h = dm.heightPixels;
        }

        float viewW = itemViewSize;
        float viewH = itemViewSize;
        int itemViewCountHorizontal = (int) (w / itemViewSize);
        int itemViewCountVertical = (int) (h / itemViewSize);
        float deltaW = 1.0f * w % itemViewSize;
        float deltaH = 1.0f * h % itemViewSize;

        viewW += deltaW / itemViewCountHorizontal;
        viewH += deltaH / itemViewCountVertical;

        int index = 0;

        for (int i = 0; i < itemViewCountVertical; i++) {

            if (i == 0 || i == (itemViewCountVertical / 2) || i == (itemViewCountVertical - 1)) {

                for (int j = 0; j < itemViewCountHorizontal; j++) {

                    TouchViewItem v = new TouchViewItem(context,
                            j * viewW, i * viewH,
                            (int) viewW, (int) viewH, index++);
                    parent.addView(v);

                }
            } else {

                for (int j = 0; j < 3; j++) {

                    float x = 0;
                    if (j == 1) {
                        x = (j * (itemViewCountHorizontal / 2.0f)) * viewW;

                    } else if (j == 2) {
                        x = ((itemViewCountHorizontal - 1)) * viewW;
                    }

                    TouchViewItem v = new TouchViewItem(context,
                            x, i * viewH,
                            (int) viewW, (int) viewH, index++);

                    parent.addView(v);
                }
            }
        }


    }


    private boolean isAllItemGone = false;
    private void checkTouchView(int x , int y){

        boolean allGone = true;
        int count = parentContainer.getChildCount();
        for (int i = 0; i < count; i ++) {
            View view = parentContainer.getChildAt(i);
            if (view instanceof TouchViewItem) {
                TouchViewItem item = (TouchViewItem) view;
                item.getHitRect(rectTemp);
                if (rectTemp.contains(x, y) && item.getVisibility() != View.GONE) {
                    item.setVisibility(View.GONE);
                }

                if (item.getVisibility() == View.VISIBLE) {
                    allGone = false;
                }
            }
        }

        if (allGone) {
            DebugLog.i("items are all gone");
            isAllItemGone = true;

            if (DeviceAttr.getRunningDeviceAttr().hasETP() && !isETP) {

                isETP = true;

                for (int i = 0; i < count; i++) {
                    View view = parentContainer.getChildAt(i);
                    if (view instanceof TouchViewItem) {
                        TouchViewItem item = (TouchViewItem) view;
                        item.setVisibility(View.VISIBLE);
                    }
                }

                showInfo();
                isAllItemGone = false;

            } else {
                finishWithOK();
            }
        }

    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int x,y;
        x = (int) event.getX();
        y = (int) event.getY();

        if( event.getAction() == MotionEvent.ACTION_UP ){
            return super.dispatchTouchEvent(event);
        }
        if (event.getPointerCount() == 1
                && !isAllItemGone
                && event.getToolType(0) == (isETP ? MotionEvent.TOOL_TYPE_STYLUS : MotionEvent.TOOL_TYPE_FINGER)) {

            checkTouchView(x, y);
        }

//        Log.e(TAG, "dispatchTouchEvent x = " + x + ",  y = " + y);
        return super.dispatchTouchEvent(event);
    }



    // Button
    public class TouchViewItem extends AppCompatTextView {
        public int mIndex;

        private void init(int index ){
            mIndex = index;
            this.setText(Integer.toString(index));
//            this.setTextSize((float)20.0);
            this.setTextColor(Color.BLACK);
            this.setGravity(Gravity.CENTER);
            this.setClickable(true);
            this.setBackgroundResource(R.drawable.selector_rect_background);
        }

        public TouchViewItem(Context context,float x, float y, int w , int h , int index ) {
            super(context);
//            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            this.setX(x);
            this.setY(y);
            this.setMinimumHeight(h);
            this.setMinimumWidth(w);
            init(index);
        }


        @Override
        public boolean performClick() {
            return super.performClick();
        }
    }


}
